package cn.sollyu.SDCardManager;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.ApplicationInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class ActivityOneKey extends Activity
{
	private final static int MSG_PROGRESS_SET_TEXT = 1;
	private final static int MSG_CLOSE_PROGRESS = 2;
	private final static int MSG_PROGRESS_SET_STYLE = 3;
	private final static int MSG_PROGRESS_SET_MAX = 4;
	private final static int MSG_PROGRESS_SET_VALUE = 6;
	private final static int MSG_LIST_UPDATE = 7;
	private final static int MSG_TOAST = 8;
	
	private ProgressDialog progressDialog;
	private Handler handler;
	private ListView listView;
	
	ArrayList<File> deleteFilesArrayList ;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		progressDialog = new ProgressDialog(ActivityOneKey.this);
		progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		progressDialog.setTitle(getString(R.string.oneKey_progressDialog_title));
		progressDialog.setMessage(getString(R.string.oneKey_progressDialog_tip_load_app));
		progressDialog.show();
		
		setContentView(R.layout.activity_onekey);
		listView = (ListView) findViewById(R.id.onekey_list);
		
		deleteFilesArrayList = new ArrayList<File>();
		handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				
				switch (msg.what) {
					case MSG_PROGRESS_SET_TEXT:
						progressDialog.setMessage((CharSequence) msg.obj);
						break;
						
					case MSG_CLOSE_PROGRESS:
						progressDialog.dismiss();
						break;
						
					case MSG_PROGRESS_SET_STYLE:
						
						break;
						
					case MSG_PROGRESS_SET_MAX:
						int max = (Integer) msg.obj;
						progressDialog.setMax(max);
						break;
						
					case MSG_PROGRESS_SET_VALUE:
						int value = (Integer) msg.obj;
						progressDialog.setProgress(value);
						break;
						
					case MSG_LIST_UPDATE:				// 刷新界面列表
						ArrayList<HashMap<String, Object>> deleList = new ArrayList<HashMap<String, Object>>();
						try
						{
							for (int i=0;i<deleteFilesArrayList.size();i++)
							{
								HashMap<String, Object>hashMap=new HashMap<String, Object>();
								hashMap.put("name", deleteFilesArrayList.get(i).getName());
								hashMap.put("icon", ServiceFileManager.getFileIcon(deleteFilesArrayList.get(i).getAbsolutePath()));
								hashMap.put("dele", ServiceDatabaseManager.getDeleAlertInfoString(deleteFilesArrayList.get(i).getAbsolutePath(), ActivityOneKey.this));
								deleList.add(hashMap);
							}
						} catch (Exception e){
							Toast.makeText(ActivityOneKey.this, "在准备显示列表时出现错误：" + e.getMessage(), 1).show();
						}
						
						SimpleAdapter simpleAdapter = new SimpleAdapter(ActivityOneKey.this, deleList, R.layout.activity_onekey_list_item, new String[] {"name","icon","dele"}, new int[] {R.id.onekey_list_name,R.id.onekey_list_icon,R.id.onekey_list_dele});
						listView.setAdapter(simpleAdapter);
						break;
						
					case MSG_TOAST:
						Toast.makeText(ActivityOneKey.this, (CharSequence) msg.obj, 1).show();
						break;
					default:
						break;
				}
				
				super.handleMessage(msg);
			}
			
		};
		
		new Thread()
		{

			@Override
			public void run() {
				

					List<ApplicationInfo> applications = getPackageManager().getInstalledApplications(0);
					ArrayList<ApplicationInfo> userPackageInfo = new ArrayList<ApplicationInfo>()  ,sysPackageInfos  = new ArrayList<ApplicationInfo>() ;
					
					for (ApplicationInfo pInfo:applications)
					{
						if ((pInfo.flags & ApplicationInfo.FLAG_SYSTEM ) == 1)
						{
							sysPackageInfos.add(pInfo);
						}else {
							userPackageInfo.add(pInfo);
						}
					}
					
					try
					{					
					handler.obtainMessage(MSG_PROGRESS_SET_TEXT,getString(R.string.oneKey_progressDialog_tip_load_app_final)).sendToTarget();
					Thread.sleep(1000);
					
					handler.obtainMessage(MSG_PROGRESS_SET_TEXT,getString(R.string.oneKey_progressDialog_tip_load_dele_list)).sendToTarget();			// 设置获取列表提示
					ArrayList<File> filesArrayList = ServiceFileManager.gerFileList("/sdcard");				// 获得内存卡根目录文件
					
					handler.obtainMessage(MSG_PROGRESS_SET_MAX,filesArrayList.size()).sendToTarget();	// 设置状态栏最大进度为内存卡跟目录文件个数
					

					// 主函数  ①取以安装软件
					// 		②获取可删除列表
					//			⒈取删除列表
					//			⒉取生成软件
					//			⒊比较是否在已安装软件列表中
					//			⒋添加可删除列表中
					int sum=0;
					for (File file:filesArrayList)			// 循环内存卡跟目录文件
					{
						handler.obtainMessage(MSG_PROGRESS_SET_VALUE,sum++).sendToTarget();
						int isDele = new Integer(ServiceDatabaseManager.getDeleisDeteString(file.getAbsolutePath(), ActivityOneKey.this));	// 获得是否被删除
						if (isDele == 1)
						{
							String soft = ServiceDatabaseManager.getSoftString(file.getAbsolutePath(), ActivityOneKey.this);				// 获得生成软件
							Boolean isInstallAppBoolean = false;											// 是否在用户安装的列表之中
							for (int userAppTemp=0;userAppTemp<userPackageInfo.size();userAppTemp++)							// 遍历安装软件目录
							{					
								ApplicationInfo pinfo = userPackageInfo.get(userAppTemp);
								String appLableString = ActivityOneKey.this.getPackageManager().getApplicationLabel(pinfo).toString();		// 获得安装软件名
								if (soft.equalsIgnoreCase(appLableString))									// 如果文件生成软件为安装软件
								{
									isInstallAppBoolean = true;											// 如果是在安装列表中，就忽略 是，置为真
									break;
								}
							}																		//遍历完安装的软件，依然为FALSE，则为可以删除目录
							if (isInstallAppBoolean == false)												// 如果不在安装列表，并可以删除
							{
								deleteFilesArrayList.add(file);												// 添加删除列表
							}
							
						}
						
					}
					
					handler.obtainMessage(MSG_PROGRESS_SET_TEXT,getString(R.string.oneKey_progressDialog_tip_load_show_dele_list)).sendToTarget();
					handler.obtainMessage(MSG_LIST_UPDATE).sendToTarget();								// 更新界面中的列表
			
				}catch (Throwable e) {
					handler.obtainMessage(MSG_TOAST, e.toString()).sendToTarget();	
					
				} 
				finally {
					handler.obtainMessage(MSG_CLOSE_PROGRESS).sendToTarget();							// 关闭加载窗口
					
				}
				
			}
			
		}.start();
		
		listView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
				LinearLayout linearLayout = (LinearLayout) ((RelativeLayout)arg1).getChildAt(2);
				TextView nameTextView = (TextView) linearLayout.getChildAt(0);
				
				String pathString = "/sdcard/" + nameTextView.getText().toString();
				new ActivityViewAlertDialgo(ActivityOneKey.this, new File(pathString)).show();
				
				
			}});
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		
		menu.add(getString(R.string.oneKey_menu_delete)).setIcon(android.R.drawable.ic_menu_delete);
		menu.add(getString(R.string.oneKey_menu_cancel)).setIcon(android.R.drawable.ic_menu_revert);
		
		return super.onCreateOptionsMenu(menu);
	}

	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		
		if (item.toString().equals(getString(R.string.oneKey_menu_cancel)))
		{
			finish();
		}else if  (item.toString().equals(getString(R.string.oneKey_menu_delete)))
		{
			String alertString = "确定删除选中？";
			Builder alertDialog = new AlertDialog.Builder(ActivityOneKey.this);
			alertDialog.setTitle(getString(R.string.oneKey_alertDialog_titile));
			alertDialog.setMessage(alertString);
			alertDialog.setPositiveButton(getString(R.string.oneKey_alertDialog_button_ok), new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					for (int i=0;i< listView.getChildCount();i++)
					{

						RelativeLayout relativeLayout = (RelativeLayout)listView.getChildAt(i);
						CheckBox checkBox =  (CheckBox) relativeLayout.getChildAt(1);
						LinearLayout linearLayout = (LinearLayout) relativeLayout.getChildAt(2);
						String nameString =((TextView) linearLayout.getChildAt(0)).getText().toString();
						 
						if (checkBox.isChecked())
						{	
							final String pathString = "/sdcard/" + nameString;
//							int isAlert = new Integer( ServiceDatabaseManager.getDeleisAlertString(pathString, ActivityOneKey.this));
//							if (isAlert == 1)
//							{
//								
//							}else {
//								ServiceFileManager.delete(pathString, ActivityOneKey.this);
//							}
							ServiceFileManager.delete(pathString, ActivityOneKey.this);
							
						}
						
					}
				}
			});
			alertDialog.setNegativeButton(getString(R.string.oneKey_alertDialog_button_cancel),  (OnClickListener)null);
			alertDialog.show().setIcon(android.R.drawable.ic_menu_help);
		}
		return super.onOptionsItemSelected(item);
	}	

	
	
}
